package cn.dt70.utils;

import javax.mail.Address;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

public class JavaMailUtil {

    public  static String account = "zhaoxing_1222@163.com";        //发件人账号(普通账户默认不启动相关发件协议，要先开启该发件邮箱相关协议的授权)
    public  static String password = "javamail000000";				//在授权后会填写相关的授权码，

    public static void sendMail(String mail,String userName,int uid,String type,String content){
            // 1. 使用Properties对象封装连接所需的信息(K,V)
        Properties props = new Properties();                    // 参数配置
        props.setProperty("mail.transport.protocol", "smtp");   // 使用的发件协议
        props.setProperty("mail.smtp.host", "smtp.163.com");   	// 发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.port","25");               //设置端口
        props.setProperty("mail.smtp.auth", "true");            // 需要请求认证

        // 2. 获取Session对象(以上面的配置为基础)
        Session session = Session.getDefaultInstance(props);    //或者Session session = Session.getInstance(props);
        session.setDebug(true);                                 // 设置为debug模式, 可以查看详细的发送 log

        // 3. 封装Message对象
        MimeMessage message = null;
        try {
            message = createMimeMessage(session, account, mail,userName,uid,type,content);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 4. 使用Transport发送邮件
        try {
            Transport transport = session.getTransport();
            transport.connect(account, password);                  //设置发件人的账户名和密码(这里用的是授权码)
            transport.sendMessage(message, new Address[]{new InternetAddress(mail)}); //只发送给指定的人;
            // 5. 关闭连接
            transport.close();
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }

    public static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail,String userName,int uid,String Type,String content) throws Exception {
        // 1. 创建一封邮件p
        MimeMessage message = new MimeMessage(session);
        // 2. From: 发件人(会在收件端的收件人项上显示sendMail的value值)
        message.setFrom(new InternetAddress(sendMail, "[爱钱帮]", "UTF-8"));
        // 3. To: 收件人(会在自己邮件服务端已发邮件头部显示)
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "用户ID:"+uid, "UTF-8"));
        // 4. Subject: 邮件主题
        message.setSubject(Type, "UTF-8");
        // 5. Content: 邮件正文
        message.setContent("尊敬的用户："+userName+"  您好！"+content, "text/html;charset=UTF-8");
        // 6. 设置发件时间
        message.setSentDate(new Date());
        // 7. 保存设置
        // message.saveChanges();
        return message;
    }
}
